<?php

namespace app\api\controller;

use app\common\model\CostBill;
use app\common\controller\Api;
use app\common\model\DinnerRecord;
use EasyWeChat\Factory;
use app\admin\model\User as UserModel;
use think\Cache;

class User extends Api
{
    protected $noNeedLogin = ['oauth_login', 'refresh_token'];
    protected $noNeedPermission = ['*'];

    public function initialize()
    {
        parent::initialize();
    }

    public function refresh_token()
    {
        $userinfo = \think\facade\Cache::get('token_' . $this->request->get('token'));
        if($userinfo){
            $this->success('成功', $userinfo);
        }
        $this->error('token过期');

    }

    public function oauth_login()
    {
        $config = [
            'app_id' => 'wx56c979d82ef6e40d',
            'secret' => '71b08c91f4f06acfa635249ae9ffb9f9',

            // 下面为可选项
            // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
            'response_type' => 'array',

            'log' => [
                'level' => 'debug',
                'file' => __DIR__ . '/wechat.log',
            ],
        ];
        //avatarUrl: "https://thirdwx.qlogo.cn/mmopen/vi_32/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg/132"
        //city: ""
        //country: ""
        //gender: 0
        //language: ""
        //nickName: "微信用户"
        //province: ""
        $app = Factory::miniProgram($config);
        $userinfo = $this->request->post('user_info');
//        print_r($userinfo);
//        exit();
        $r = $app->auth->session($this->request->post('code'));
        if (!UserModel::where(['openid' => $r['openid']])->value('id')) {
            UserModel::create(['openid' => $r['openid']]);
        }
        $userinfo = UserModel::where(['openid' => $r['openid']])->find();
        $userinfo['token'] = $r['session_key'];
        \think\facade\Cache::set('token_' . $r['session_key'], $userinfo);
        $res = $this->auth->login($r['openid']);
        if ($res) {
            $this->success(__('Login succeeded!'), [
                'userinfo' => $this->auth->getInfo(),
                'routeName' => 'admin'
            ]);
        }

        $msg = $this->auth->getError();
        $msg = $msg ? $msg : __('Incorrect user name or password!');
        $this->error($msg);
    }

    public function get_user_info()
    {
        $user = UserModel::find($this->auth->id);
        $user['team'] = $user['group_id'] == 1 ? ['name' => '武汉市十里家园拼餐组'] : ['name' => '游客'];
        $this->success('成功', $user);
    }

    public function get_dinner_record()
    {

        $days = array_reverse(get_day(date('Y-m-d'), 2));
        foreach ($days as $key => $value) {
            $data[$key]['date'] = $value;
            $data[$key]['count'] = DinnerRecord::where(['date' => $value, 'user_id' => $this->auth->id])->count('id');
            $data[$key]['list'] = DinnerRecord::with(['user'])->where(['date' => $value, 'user_id' => $this->auth->id])->select();
            foreach ($data[$key]['list'] as $k => $v) {
                $uid_arr = DinnerRecord::where(['date' => $value, 'type' => $v['type'],])->whereNotIn('user_id', $this->auth->id)->column('user_id');
//               echo(new DinnerRecord())->getLastSql();
//               print_r($uid_arr);
                $data[$key]['list'][$k]['other_user'] = \app\admin\model\User::whereIn('id', $uid_arr)->select();
            }
        }
//echo (new \app\admin\model\User())->getLastSql();
        $this->success('成功', $data);
    }


    public function get_my_bill()
    {
        $days = array_reverse(get_day(date('Y-m-d'), 2));

        foreach ($days as $key => $value) {
            $bill_list[$key]['date'] = $value;
            $bill_list[$key]['cost'] = CostBill::whereBetween('create_time', [strtotime($value), strtotime($value) + 24 * 3600])->where(['user_id' => $this->auth->id])->sum('amount');
            $bill_list[$key]['list'] = CostBill::with(['user'])->whereBetween('create_time', [strtotime($value), strtotime($value) + 24 * 3600])->where(['user_id' => $this->auth->id])->select();
        }

        $this->success('成功', $bill_list);
    }

    public function update_my_info(){
        $post=$this->request->post();
        UserModel::where(['id'=>$this->auth->id])->update(['birthday'=>$post['birthday'],'avatar'=>$post['avatar'],'gender'=>$post['gender']]);
        $this->success();
    }

    public function get_statistic_data()
    {
        $arr = [];

        $list = CostBill::select();

        foreach ($list as $key => $value) {
            $arr[] = str_replace(' ', ',', str_replace('、', ',', str_replace('，', ',', $value['summary'])));
        }
        $str = implode(',', $arr);
        $new_arr = explode(',', $str);
        //print_r($new_arr);
//$new_arr=array_merge(array_merge(array_merge(array_merge($arr,$arr1),$arr2),$arr3),$arr4);
        $count_values = array_count_values($new_arr);
        foreach ($count_values as $key => $value) {
            $count[] = ['name' => $key, 'textSize' => $value *4];
        }
        $days = get_weeks(7);
        $dinners = [1 => '早餐', 2 => '中餐', 3 => '晚餐'];
        foreach ($dinners as $key => $value) {
            $dinner[$key - 1]['name'] = $value;
            $dinner[$key - 1]['data'] = DinnerRecord::where(['type' => $key, 'user_id' => $this->auth->id])->count('id');
        }
        foreach ($days as $key => $value) {
            $chart_data['categories'][] = substr($value, -5);
            $chart_data['series'][0]['data'][] = CostBill::whereBetween('create_time', [strtotime($value), strtotime($value) + 24 * 3600])->sum('amount');
            $chart_data['series'][1]['data'][] = CostBill::whereBetween('create_time', [strtotime($value), strtotime($value) + 24 * 3600])->where(['user_id' => $this->auth->id])->sum('amount');
        }
        $chart_data['series'][0]['name'] = '团队采购金额';
        $chart_data['series'][1]['name'] = '本人采购金额';
        $data['chart_data'] = $chart_data;
        $data['dinner'] = $dinner;
        $data['word_data'] = $count;
        $this->success('成功', $data);
    }


    public function get_member_list()
    {
        $this->success('成功', UserModel::where(['group_id'=>1])->whereNotIn('id', $this->auth->id)->select());
    }


}